package com.fan.common_base;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;

import com.fan.base.IComponentApplication;

import java.util.List;

/**
 * thirdParty
 *
 * @author fan
 * @date Created in 2019-09-23
 */
public class BaseApplication extends Application {


    private static final String[] MODULE_LIST = { "com.fan.push.PushApplication",
            "com.fan.share.ShareApplication" };

    /**
     * 全局唯一的context
     */
    public static BaseApplication mBaseApplication;

    @Override
    protected void attachBaseContext ( Context base ) {
        super.attachBaseContext( base );
        mBaseApplication = this;
    }

    @Override
    public void onCreate () {
        super.onCreate();
        if ( shouldInit() ) {
            modulesApplicationInit();
            initBaseApplication();
        }
    }

    public void initBaseApplication () {

    }

    /**
     * 获取当前Process的名称，如果不是自己想要的，就直接return
     *
     * @return boolean
     */
    private boolean shouldInit () {
        ActivityManager am = ( (ActivityManager) getSystemService( Context.ACTIVITY_SERVICE ) );
        List< ActivityManager.RunningAppProcessInfo > processInfo = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();
        for ( ActivityManager.RunningAppProcessInfo info : processInfo ) {
            if ( info.pid == myPid && mainProcessName.equals( info.processName ) ) {
                return true;
            }
        }
        return false;
    }

    public static BaseApplication getInstance () {
        return mBaseApplication;
    }

    /**
     * 反射得到实现IComponentApplication接口的init方法
     */
    private void modulesApplicationInit () {
        for ( String moduleImpl : MODULE_LIST ) {
            try {
                Class< ? > clazz = Class.forName( moduleImpl );
                Object obj = clazz.newInstance();
                if ( obj instanceof IComponentApplication ) {
                    ( (IComponentApplication) obj ).init( BaseApplication.getInstance() );
                }
            } catch ( ClassNotFoundException e ) {
                e.printStackTrace();
            } catch ( IllegalAccessException e ) {
                e.printStackTrace();
            } catch ( InstantiationException e ) {
                e.printStackTrace();
            }
        }
    }
}
